<!--睡眠分期图-->
<template>
  <div id="sleep-chart" class="chart">
    <div class="title-div">
      <span class="title">睡眠分期图</span>
    </div>
  </div>
</template>

<script lang="ts" setup>
import {defineProps, reactive, watch} from 'vue';
import * as echarts from 'echarts';
import moment from 'moment';

import {formatToWeek, numberToTime} from '@/utils/dates';

const props = defineProps({
  chartData: {
    type: Array,
    default: [],
  },
  dateRange: null as any,
  startTime: null as any
});

const state = reactive({
  chartData: [],
  dateRange: null as any,
  startTime: null as any
})

watch(
    () => [props.dateRange, props.startTime, props.chartData],
    ([dateRange, startTime, chartData]) => {
      if (dateRange) {
        state.dateRange = dateRange
        setTimeout(() => {
          initSleep(parseInt(state.dateRange), startTime, state.chartData);
        })
      }
      if (startTime) {
        state.startTime = startTime
        setTimeout(() => {
          initSleep(parseInt(state.dateRange), startTime, state.chartData);
        })
      }
      if (chartData) {
        state.chartData = chartData
        setTimeout(() => {
          initSleep(parseInt(state.dateRange), startTime, state.chartData);
        })
      }
    },
);

const initSleep = (dateRange: number, time: string, chartData = [] as any) => {
  console.log('props.chartData', chartData)
  if (!time || chartData.length === 0) {
    return
  }
  let awaken = [] as any
  let movement = [] as any
  let light = [] as any
  let deep = [] as any
  let sober = [] as any
  let xAxisData = [] as any
  let startTime = moment(time)
  let dateTime = moment()
  //计算相差的分钟数
  const day = dateTime.diff(startTime, 'days');
  const max = dateRange === 2 ? 7 : day
  // t_wake_time
  for (let i = 0; i < max; i++) {
    const time = startTime.add(i === 0 ? i : 1, 'days').format('YYYY-MM-DD')
    xAxisData.push(dateRange === 2 ? formatToWeek(new Date(time)) : time)
    const charts = chartData.filter(({
                                       tWakeTime,
                                       iMainSleepFlag
                                     }) => moment(tWakeTime).format('YYYY-MM-DD') === time && [1, 101].includes(iMainSleepFlag))
    console.log('xAxisData', charts)
    let four = 0, three = 0, two = 0, one = 0, zero = 0
    charts.forEach((sleep: any, index: number) => {
      sleep.mtSleepStage.split(',').forEach((v: any, i: number) => {
        switch (parseInt(v)) {
          case 0:
            zero += 1
            break
          case 1:
            one += 1
            break
          case 2:
            two += 1
            break
          case 3:
            three += 1
            break
          default:
            four += 1
            break
        }
      })
    })
    awaken.push(three)
    movement.push(two)
    light.push(one)
    deep.push(zero)
    sober.push(four)
  }
  // 初始化 图表
  init(xAxisData, awaken, movement, light, deep, sober);
}

/**
 * 初始化函数
 * */
const init = async (xAxisData = [], awaken = [], movement = [], light = [], deep = [], sober = []) => {
  const chart = echarts.init(document.getElementById('sleep-chart'));
  //三种状态的颜色
  let colors = ["#6D6DF1", "#5384FE", "#7DA6FE", "#FFC03A", '#FF0000'];
  //三种状态
  chart.setOption({
    title: {
      text: '睡眠分期图'
    },
    color: colors,
    tooltip: {
      //提示框
      formatter(params: any) {
        if (params.length === 0) {
          return ''
        }
        let week = '';
        let content = ''
        let count = 0
        params.forEach(({seriesName, value, name}, index: number) => {
          if (!week) {
            week = name;
          }
          if (content) {
            content += '<br/>'
          }
          count += parseInt(value) * 45
          content += `${seriesName}：` + numberToTime(parseInt(value) * 45)
        })
        if (count > 0) {
          content = numberToTime(count) + '<br/>' + content
        }
        return `${week}<br/>总睡眠时长：${content}`;
      },
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {},
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        data: xAxisData
      }
    ],
    yAxis: [
      {
        type: 'value'
      }
    ],
    series: [
      {
        name: '深睡',
        type: 'bar',
        stack: 'Ad',
        barMaxWidth: 20,
        data: deep
      },
      {
        name: '浅睡',
        type: 'bar',
        stack: 'Ad',
        barMaxWidth: 20,
        data: light
      },
      {
        name: '快速眼动',
        type: 'bar',
        stack: 'Ad',
        barMaxWidth: 20,
        data: movement
      },
      {
        name: '觉醒',
        type: 'bar',
        stack: 'Ad',
        barMaxWidth: 20,
        data: awaken
      },
      {
        name: '清醒',
        type: 'bar',
        stack: 'Ad',
        barMaxWidth: 20,
        data: sober
      },
    ]
  });
};
</script>

<style lang="less" scoped>
.chart {
  position: relative;
  border: 1px solid rgba(198, 202, 209, 0.5);
  border-radius: 8px;
  padding: 70px 20px 20px 20px;
  height: 420px;

  .title-div {
    position: absolute;
    top: 10px;
    left: 20px;
    display: flex;
    flex-direction: column;

    .title {
      font-weight: bold;
      color: rgba(0, 0, 0, 0.6);
      margin-bottom: 10px;
    }

    .unit {
      color: #8b96a6;
      font-size: 12px;
    }
  }
}
</style>
